package com.borya.service.web.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.borya.dao.WhiteListDAO;
import com.borya.framework.annotation.Autowired;
import com.borya.framework.annotation.Component;
import com.borya.model.db.Merchant;
import com.borya.model.db.WhiteConfig;
import com.borya.model.entity.PageArgs;
import com.borya.model.entity.PageData;
import com.borya.model.entity.WhiteProd;
import com.borya.service.web.WhiteListService;
import com.borya.util.StringUtil;
@Component("whiteListServiceImpl")
public class WhiteListServiceImpl implements WhiteListService {

	private Logger log = Logger.getLogger(getClass());
	
	@Autowired("whiteListDAOImpl")
	private WhiteListDAO whiteListDAO;
	
	public WhiteListDAO getWhiteListDAO() {
		return whiteListDAO;
	}

	public void setWhiteListDAO(WhiteListDAO whiteListDAO) {
		this.whiteListDAO = whiteListDAO;
	}
	@Override
	public boolean addWhiteProd(WhiteProd whiteProd){
		return getWhiteListDAO().addWhiteProd(whiteProd);
	}

	@Override
	public List<WhiteProd> findWhiteProdList() throws Exception {
		return getWhiteListDAO().findWhiteProdList();
	}

	@Override
	public boolean deleteWhiteProd(String prodId) {
		return getWhiteListDAO().deleteWhiteProd(prodId);
	}

	@Override
	public boolean isUsedWhiteProdId(String prodId) {
		return getWhiteListDAO().isUsedWhiteProdId(prodId);
	}

	@Override
	public PageData<Merchant> getMerchantConfigByPage(String dealerId,PageArgs pageArgs){
		return getWhiteListDAO().getMerchantConfigByPage(dealerId,pageArgs);
	}

	@Override
	public List<WhiteConfig> StructureScopes(String dealerId) {
		return getWhiteListDAO().StructureScopes(dealerId);
	}

	@Override
	public boolean updateScopeConfig(String configId, String isLocal, String whiteIds) throws Exception {
		//校验whiteIds中所有白名单是否存在
		if(!StringUtil.isNULL(whiteIds)){
			List<String> outerInput = Arrays.asList(whiteIds.split(","));
			String selIds=getWhiteListDAO().checkWhiteIdsExist(whiteIds);
			if(!whiteIds.equals(selIds)){
				String deletedIds="";
				if(selIds==null)
					deletedIds= whiteIds;
				else{
					List<String> collect = outerInput.stream().filter(e->!selIds.contains(e)).collect(Collectors.toList());
					deletedIds=StringUtils.join(collect.toArray(), ",");
							
				}
				if(!StringUtil.isNULL(deletedIds)){
					log.warn("白名单编号："+deletedIds+"不存在，可能被删除除");
					throw new Exception("白名单编号："+deletedIds+"不存在，可能被删除除，请重新编辑商户售卡区域配置项");
				}
			}
		}
		//选择的whiteIds没问题，更新操作
		return getWhiteListDAO().updateScopeConfig(configId,isLocal,whiteIds);
	}

}
